#!/usr/bin/ruby
require 'net/imap'
require 'net/smtp'

class ScreenShotByMail
  def initialize
    @rightSender="sender's email address" #you need to change this
    @rightSubject="Screenshot" #you may change this

    @username = 'my_username' #you need to change this
    @password = 'my_password' #you need to change this
    @server = 'my_server' #you need to change this
    @port = 993   #you may change this
    @useSSL=true #you may change this

    imap = Net::IMAP.new(@server,@port,@useSSL)
    imap.login(@username, @password)
    imap.select('INBOX')
      imap.search(["UNSEEN"]).each do |message_id|
         envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
          fromEmail= "#{envelope.from[0].mailbox}@#{envelope.from[0].host}"
          if fromEmail.eql?(@rightSender) && envelope.subject.eql?(@rightSubject)
            sendScreenShot
            puts "marking asseen and deleted #{envelope.from[0].mailbox}@#{envelope.from[0].host}\t#{envelope.subject}"
            imap.store(message_id, "+FLAGS", [:Seen,:Deleted])
          end
      end


      imap.logout()
  end
  
  def sendScreenShot
    puts 'Taking screenshot'
    filename='/screenie.png'
    
    `screencapture -tjpg #{filename}`
    
    
    # Read a file and encode it into base64 format
    filecontent = File.read(filename)
    encodedcontent = [filecontent].pack("m")   # base64

    marker = "AUNIQUEMARKER"
    configString=`ifconfig`
    body =<<EOF111
The screen shot is attached

ifconfig:

#{configString}
EOF111

    # Define the main headers.
    part1 =<<EOF
From: radif.sharafullin@savantav.com
To: #{@rightSender}
Subject: Re: #{@rightSubject}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF

    # Define the message action
    part2 =<<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit

#{body}
--#{marker}
EOF

    # Define the attachment section
    part3 =<<EOF
Content-Type: multipart/mixed; name=\"#{filename}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{filename}"

#{encodedcontent}
--#{marker}--
EOF

    mailtext = part1 + part2 + part3

    # Let's put our code in safe area
    begin 
      puts "sending message..."
       Net::SMTP.start(@server) do |smtp|
         smtp.sendmail(mailtext, 'radif.sharafullin@savantav.com',
                              [@rightSender])
      end
    rescue Exception => e  
      print "Exception occured: " + e  
    end

    `rm #{filename}`

  end
end

while
ScreenShotByMail.new
sleep 30
end
#ScreenShotByMail.new
